# -*- coding: utf-8 -*-
from flask import Blueprint, jsonify, request
from flasgger import swag_from
from ..utils import make_response, search_web_link, xiaozhi_response, get_bing_search_results, \
    get_bochaai_search_results

bp = Blueprint('funcSearch', __name__)

def perform_search(search_type, content):
    """
    Helper function to perform web search using different search engines.
    """
    if search_type == 'bocha':
        print('Performing Google search...')
        search_result = get_bochaai_search_results(content)
        if search_result:
            response_content = search_result
            print(f'Search result from Google: {response_content}')

            query = f"""
                现在你是一个问答机器人,我会给你一段来自互联网的文本,你根据这段文本和用户的问题来进行回答,如果文本提供的内容回答不了用户的问题,那么则回答我无法提供正确的回答
            网络资料:
             ------------------------------------------
            {response_content}
             ------------------------------------------
             用户问题：
             {content}
            """


            return xiaozhi_response(query)
        else:
            return make_response(message="Failed to retrieve search results from Google", status=500)
    elif search_type == 'bing':
        print('Performing Bing search...')
        filter_words = ['查询', '帮我', '获取']

        # Filter out unnecessary words
        filtered_content = content
        for word in filter_words:
            filtered_content = filtered_content.replace(word, '')

        bing_results = get_bing_search_results(filtered_content)
        if bing_results:
            print(f'Bing search results: {bing_results}')
            query = f"""
                现在你是一个问答机器人,我会给你一段来自互联网的文本,你根据这段文本和用户的问题来进行回答,如果文本提供的内容回答不了用户的问题,那么则回答我无法提供正确的回答
            网络资料以下链接也整理，不要出现’根据您提供的网络资料‘者一类的描述:
             ------------------------------------------
            {bing_results}
             ------------------------------------------
             用户问题：
             {content}
            """
            return xiaozhi_response(query)
        else:
            # Fallback to another search method if Bing results are not available
            search_result = get_bochaai_search_results(content)
            if search_result:
                response_content = search_result
                print(f'Search result from Bing alternative: {response_content}')
                return xiaozhi_response(response_content)
            else:
                return make_response(message="Failed to retrieve search results from Bing", status=500)
    else:
        print('Unknown search type or default handling.')
        return xiaozhi_response(content)

@bp.route('/search/frominternet', methods=['POST'])
@swag_from({
    'parameters': [
        {
            'name': 'messages',
            'in': 'body',
            'required': True,
            'schema': {
                'type': 'object',
                'properties': {
                    'model': {
                        'type': 'string',
                        'example': 'llama3'
                    },
                    'messages': {
                        'type': 'array',
                        'items': {
                            'type': 'object',
                            'example': {"role": "bocha", "content": "查询黑神话悟空相关信息"}
                        }
                    }
                }
            },
            'description': '输入消息数组，通常包含用户的查询内容role:[google,bing,不填默认（小智回答）]'
        }
    ],
    'responses': {
        200: {
            'description': 'Successful Response',
            'examples': {
                'application/json': {
                    "choices": [
                        {
                            "finish_reason": "stop",
                            "index": 0,
                            "message": {
                                "content": "你好！有什么我可以帮助你的吗？",
                                "role": "assistant",
                                "tool_calls": ""
                            }
                        }
                    ],
                    "created": 1724298149,
                    "id": "chatcmpl-40da0c2bbe364987b33a182326229ac4",
                    "model": "llama3",
                    "object": "chat.completion",
                    "usage": {
                        "completion_tokens": 11,
                        "prompt_tokens": 13,
                        "total_tokens": 24
                    }
                }
            }
        }
    }
})
def search_from_internet():
    """
    搜索信息互联网
    ---
    tags:
      - 联网查询功能
    """
    try:
        data = request.get_json()
        content = data['messages'][0]['content']
        role = data['messages'][0].get('role', '').lower()

        if role in ['bocha', 'bing']:
            return perform_search(role, content)
        else:
            print('Returning default response...')
            return xiaozhi_response(content)

    except Exception as e:
        print(f'Error occurred: {str(e)}')
        return make_response(message=str(e), status=500)

@bp.route('/search/hello', methods=['GET'])
@swag_from({
    'responses': {
        200: {
            'description': 'Successful Response',
            'examples': {
                'application/json': {
                    'message': 'Hello World'
                }
            }
        }
    }
})
def hello():
    """ 测试接口 hello world """
    return make_response(message='Hello World')
